<?php

namespace app\admin\service;

use app\admin\model\ConfigFieldModel;
use app\admin\model\ConfigModel;
use Exception;
use think\facade\Cache;
use think\facade\Db;

class ConfigService extends BaseService
{
    private static $cacheTag; //缓存配置tag

    /**
     * 更新配置
     *
     * @Author tanruizheng
     * @DateTime 2021-07-15
     * @param [type] $params
     * @return void
     */
    public static function updateConfig($params)
    {
        foreach ($params as $key => $value) {
            ConfigModel::where('varname', $key)->save(['value' => $value]);
        }
        return self::createSuccess('更新成功');
    }

    /**
     * 获取配置信息
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @param [type] $key
     * @param boolean $enableCache
     * @return void
     */
    public static function getConfig($key = null, $enableCache = false)
    {
        $cacheKey = self::getConfigCacheKey($key);
        if ($enableCache && !is_array($key)) {
            $data = Cache::get($cacheKey);
            if ($data) {
                return self::createSuccess('success', $data);
            }
        }
        if (empty($key)) {
            //查询全部配置
            $data = ConfigModel::column('value', 'varname');
        } else {
            if (is_array($key)) {
                //查询多个配置
                $data = ConfigModel::where('varname', 'IN', $key)->column('value', 'varname');
            } else {
                //查询单个配置
                $data = ConfigModel::where('varname', $key)->value('value');
            }
        }
        if ($enableCache && !is_array($key)) {
            Cache::tag(self::$cacheTag)->set($cacheKey, $data);
        }
        return self::createSuccess('success', $data);
    }

    /**
     * 获取扩展配置
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @return void
     */
    public static function getConfigField()
    {
        $list = ConfigFieldModel::select()->toArray();
        $configList = self::getConfig(null)['data'];
        foreach ($list as &$item) {
            $item['setting'] = unserialize($item['setting']);
        }
        return self::createSuccess($list);
    }


    /**
     * 添加或编辑扩展配置
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @param [type] $params
     * @return void
     */
    public static function addOrEditData($params)
    {
        Db::startTrans();
        try {
            if (!$params['title']) {
                return self::createFail('名称不能为空!');
            }
            //选项信息
            $opt = [];
            if ($params['options']) {
                $options = explode("\n", $params['options']);
                foreach ($options as $value) {
                    $item = explode('|', $value);
                    $arr['title'] = $item[0];
                    $arr['value'] = $item[1];
                    $opt[] = $arr;
                }
            }

            if ($params['type'] == 'radio' || $params['type'] == 'select') {
                if (!$opt) {
                    return self::createFail('选项信息格式错误!');
                }
            }
            $setting = [
                'title' => $params['title'],
                'tips' => $params['tips'],
                'options' => $opt
            ];
            $data = [
                'fieldname' => $params['fieldname'],
                'type' => $params['type'],
                'setting' => serialize($setting),
            ];
            if (isset($params['fid']) && $params['fid']) {
                $oldFieldname = ConfigFieldModel::where('fid', $params['fid'])->value('fieldname');
                $res1 = ConfigFieldModel::where('fid', $params['fid'])->save($data);
                $res2 = ConfigModel::where('varname', $oldFieldname)->save([
                    'varname' => $params['fieldname'],
                    'info' => $params['title'],
                ]);
            } else {
                $data['createtime'] = time();
                $res1 = ConfigFieldModel::create($data);
                $res2 = ConfigModel::create([
                    'varname' => $params['fieldname'],
                    'info'    => $params['title'],
                    'group'   => 2,
                    'value'   => ''
                ]);
            }
            if ($res1 !== false && $res2 !== false) {
                Db::commit();
                return self::createSuccess('更新成功');
            } else {
                Db::rollback();
                return self::createSuccess('更新失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            return self::createFail($e->getMessage());
        }
    }

    /**
     * 获取扩展配置信息
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @param [type] $fid
     * @return void
     */
    public static function configFieldData($fid)
    {
        $detail = ConfigFieldModel::where('fid', $fid)->find()->toArray();
        $detail['setting'] = unserialize($detail['setting']);
        if (isset($detail['setting']['options']) && $detail['setting']['options']) {
            $options = $detail['setting']['options'];
            $opt = [];
            foreach ($options as $key => $value) {
                $arr = $value['title'] . '|' . $value['value'];
                $opt[] = $arr;
            }
            $detail['setting']['options'] = implode("\n", $opt);
        } else {
            $detail['setting']['options'] = '';
        }
        return self::createSuccess($detail);
    }

    /**
     * 清除配置文件缓存
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @return void
     */
    public static function clearConfigCache()
    {
        Cache::tag(self::$cacheTag)->clear();
    }

    /**
     * 获取配置文件缓存key
     *
     * @Author tanruizheng
     * @DateTime 2021-07-23
     * @param [type] $key
     * @return void
     */
    public static function getConfigCacheKey($key)
    {
        if (empty($key)) {
            return 'ConfigCache_';
        } elseif (is_string($key)) {
            return 'ConfigCache_' . $key;
        }
        return false;
    }

    /**
     * 删除扩展配置
     *
     * @Author tanruizheng
     * @DateTime 2021-07-29
     * @param [type] $fid
     * @return void
     */
    public static function deleteExtend($fid)
    {
        Db::startTrans();
        try {
            if (empty($fid)) {
                throw new Exception('参数不能为空');
            }
            $data = ConfigFieldModel::where('fid', $fid)->find()->toArray();
            if (empty($data)) {
                throw new Exception('配置信息不存在');
            }
            ConfigFieldModel::where('fid', $fid)->delete();
            ConfigModel::where('varname', $data['fieldname'])->delete();
            // 提交事务
            Db::commit();
            return self::createSuccess('删除成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return self::createFail($e->getMessage());
        }
    }
}
